package io.xxx.omni.osc.common

import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
import org.apache.commons.codec.digest.DigestUtils
import java.time.LocalDateTime
import java.util.*

fun Number?.format(): String? {
    if (this == null) {
        return null
    }
    return numberFormat.format(this)    // #,##0.00
}

fun LocalDateTime?.format(): String? {
    if (this == null) {
        return null
    }
    return this.format(dateTimeFormatter)   // yyyy-MM-dd HH:mm:ss
}

fun Date?.format(): String? {
    if (this == null) {
        return null
    }
    return dateFormat.format(this)  // yyyy-MM-dd HH:mm:ss
}

fun String.toLocalDateTime(): LocalDateTime {
    return LocalDateTime.parse(this, dateTimeFormatter)
}

fun Long.toLocalDateTime(): LocalDateTime {
    return LocalDateTime.ofEpochSecond(this / 1000, (this % 1000).toInt(), zoneOffset)
}

fun Date.toLocalDateTime(): LocalDateTime {
    return LocalDateTime.ofInstant(this.toInstant(), zoneOffset)
}

fun Any?.toJSONString(): String? {
    return when (this) {
        null -> null
        is String -> this
        else -> JSON.toJSONStringWithDateFormat(this, dateTimeFormatPattern)
    }
}

@Suppress("UNCHECKED_CAST")
fun Any.toJSONObject(): JSONObject {
    return when (this) {
        is String -> JSON.parseObject(this)
        is Map<*, *> -> JSONObject(this as Map<String, *>)
        else -> JSON.parseObject(JSON.toJSONStringWithDateFormat(this, dateTimeFormatPattern))
    }
}

fun sign(appSecret: String, signMap: Map<String, Any>): String {
    val map = if (signMap is TreeMap) signMap else TreeMap(signMap)
    val builder = StringBuilder()
        .append(appSecret)
        .append(map.entries.joinToString("") { it.key + it.value })
        .append(appSecret)
    return DigestUtils.md5Hex(builder.toString()).uppercase()
}